# -*- coding = utf-8 -*-
# @Time：2022/3/11 20:00
# @Author：3ic
# @File：instructor.py.py
# @Software：PyCharm
import json
import time
from multiprocessing import Process

import numpy as np

from iclogger import IcLogger
from window_options import fastCapture, screen, cap_hwnd


class Instructor(Process):
    _logger = IcLogger('logs/instructor.logs')

    def __init__(self, timeline, time_point_pipe, sec_msg_pipe, scan_interval: float, speedup_leisure: bool):
        Process.__init__(self)
        self.sec_hash = None
        with open('sec_hash_data/sec_hash1920x1030.json', 'r') as f_obj:
            tmp_json = json.load(f_obj)
            self.sec_hash = {}
            for k in tmp_json:
                self.sec_hash[int(k)] = tmp_json[k]
        self._timeline = timeline
        self._time_point_pipe = time_point_pipe
        self._sec_msg_pipe = sec_msg_pipe

        self._scan_interval = scan_interval
        self._speedup_leisure = speedup_leisure

    def run(self):
        Instructor._logger.info('\n\n=== instructor开始工作 ===')
        try:
            # 导入时间轴
            timeline = self._timeline
            # 倒计时末尾数字的哈希映射
            sec_hash = self.sec_hash

            # 当前时间、当前帧数、操作点编号、加速模式、加速状态标记、识别间隔（扫描间隔）
            sec = 91
            frame_cnt = 0
            tid = 0
            speedup_leisure = self._speedup_leisure
            speedup_flag = -1
            scan_interval = self._scan_interval

            # 读秒、计帧、发送秒数信息、要执行任务
            time_point = timeline[tid]
            while time_point[0] > 0:
                frame_cnt += 1
                img = fastCapture(screen, cap_hwnd, 1550, 72, 50, 20)
                hash_val = (np.sum(img[:, :, 0] < 90) << 16) + \
                           (np.sum(img[:, :, 1] < 80) << 8) + \
                           (np.sum(img[:, :, 2] < 80))

                if sec_hash.get(hash_val, sec) != sec:
                    sec = sec_hash.get(hash_val)
                    # 发送秒数信息
                    self._sec_msg_pipe.send((sec, frame_cnt))
                    frame_cnt = 0

                if sec == time_point[0] and frame_cnt == time_point[1]:
                    Instructor._logger.info('发送操作' + str(time_point[0]))
                    # 发送执行任务
                    self._time_point_pipe.send(time_point)
                    tid += 1
                    time_point = timeline[tid]
                elif sec < time_point[0]:
                    # 模拟器卡顿，越过的时间刚好是操作的执行时间，操作未能按时执行
                    # 让秒表显示未执行的时间点，然后退出
                    Instructor._logger.info('未执行操作' + str(time_point[0]))
                    self._sec_msg_pipe.send((time_point[0], -1))
                    break
                elif speedup_leisure and (sec - time_point[0] - 2) * speedup_flag < 0:
                    Instructor._logger.info('加/减速' + str(time_point[0]))
                    speedup_flag *= -1
                    # 发送加速指令
                    self._time_point_pipe.send((1, 1, 7, speedup_flag))
                time.sleep(scan_interval)
            self._time_point_pipe.send((-1, -1))
            self._sec_msg_pipe.send((-1, -1))
        except BaseException as e:
            Instructor._logger.warning(e)
